(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('appInit', appInit);

    function appInit(localStore, $state, $ionicPlatform, $rootScope, xhr, userService, chatInterval, $timeout, $ionicHistory) {
        function init() {
            var isStart = localStore.get('isStart');
            $rootScope.downloadImg = function(img) {
                return config.api + "HealthInquiry/" + img;
            }

           
            $rootScope.go = function(router) {
                $state.go(router);
            }
            $ionicPlatform.on("resume", function(event) {});
            $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, formParams) {

                var path = "";
                for (var i = 0; i < $state.$current.path.length; i++) {
                    path += $state.$current.path[i].url.source + "--->";
                }
                isStart = localStore.get('isStart');
                if (toState != 'chat') {
                    clearInterval(chatInterval.interval)
                }
                if (!isStart && toState.name != "loading") {
                    $state.go('loading');
                    event.preventDefault();
                    return;
                }

                var user = localStore.get("user");
                var userType = localStore.get("userType");




                if (user && angular.equals(toState.name, 'login')) {
                    $state.go("tabs.home");
                    event.preventDefault();
                    return;
                } else if (!user && !config.loginWhiteList[toState.name]) {
                    $state.go("login");
                    event.preventDefault();
                    return;
                }

                // if (toState.name == "other-hospital" && fromState.name == "select-hospital") {
                //  $state.go("user-info");
                //  event.preventDefault();
                //  return;
                // };
                if (config.userDocState[toState.name]) {
                    //医生帐号
                    if (userType == 2) {
                        console.log("jump to doctor");
                        $state.go(toState.name + "-doc");
                        event.preventDefault();
                        return;
                    }
                }
                if (fromState.name === 'register-doc-info-succ' && toState.name === 'register-doc-info') {
                    $state.go('login');
                    event.preventDefault();
                    return;
                }
            });
        }
        return {
            init: init
        };
    }
})();
(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('userService', userService);

    function userService(xhr, $q, localStore) {
        var userInfo = {};

        function get(userId) {
            var defer = $q.defer();

            return defer.promise;
        }

        return {
            get: get,
            userInfo: userInfo
        }
    }
})();

(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('popup', function($ionicPopup, $ionicActionSheet) {
            function alert(msg) {
                return $ionicPopup.alert({
                    template: msg,
                    cssClass: 'yd-popup',
                    okText: "确认"
                })
            }

            function confirm(content, okText, cancelText) {
                return $ionicPopup.confirm({
                    template: content,
                    cssClass: 'yd-popup',
                    okText: okText || "确认",
                    cancelText: cancelText || "取消"
                });
            }

            function sheet(title, buttons, callback, cancelCallBack) {
                $ionicActionSheet.show({
                    buttons: buttons,
                    titleText: title,
                    cancelText: "取消",
                    cancel: function() {
                        if (cancelCallBack) {
                            cancelCallBack();
                        }
                    },
                    buttonClicked: function(index) {
                        if (callback) {
                            callback(index)
                        }
                        return true;
                    }
                });
            }
            return {
                alert: alert,
                sheet: sheet,
                confirm: confirm
            }
        })
})();
(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('guid', function() {
            function Guid() {
                return (((1 + Math.random()) * 0x10000) | 0)
                    .toString(16)
                    .substring(1);
            }

            function get() {
                return Guid() + Guid();
            }
            return {
                get: get
            }
        })
})();
(function() {
    'user strict';
    angular
        .module("ydApp")
        .factory("localStore", function() {
            function save(key, data) {
                window.localStorage[key] = JSON.stringify(data);
            }

            function del(key) {
                window.localStorage.removeItem(key);
            }

            function get(key) {
                var data = window.localStorage[key] || '';
                if (data) {
                    return eval("(" + data + ")");
                }
                return null;
            }

            function clear() {
                for (var local in window.localStorage) {
                    window.localStorage.removeItem(local);
                };
                alert("清除成功");
                window.location.reload();
            }
            return {
                save: save,
                get: get,
                del: del,
                clear: clear
            }
        })
})();

(function() {
    'use strict';
    angular
        .module('ydApp')
        .factory('xhr', xhrService, ['$http', '$q']);

    function xhrService($http, $q, popup, $ionicLoading) {
        function post(routeName, params) {
            params = params || {};
            var deferred = $q.defer();
            $http({
                    method: "POST",
                    url: config.api + routeName,
                    data: params
                })
                .then(function(response) {
                    $ionicLoading.hide();
                    if (response.data.successful) {
                        deferred.resolve(response.data);
                    } else {
                        popupError(response.data.resultMsg)
                        deferred.reject(response.data.resultMsg);
                    }
                }, function(err) {
                    $ionicLoading.hide();
                    deferred.reject(err);
                })
            return deferred.promise;
        }

        function get(routeName, params, noPopup) {
            var strParams = "?";
            for (var key in params) {
                if (params[key] == null) {
                    continue;
                }
                strParams += key + "=" + params[key] + "&";
            }
            if (strParams.length > 1) {
                strParams = strParams.substring(0, strParams.length - 1);
            }
            var url = config.api + routeName + strParams;
            var deferred = $q.defer();
            $http({
                    method: "GET",
                    url: url
                })
                .then(function(response) {
                    $ionicLoading.hide();
                    if (response.data.successful) {
                        deferred.resolve(response.data);
                    } else {
                        if (!noPopup) {
                            popupError(response.data.resultMsg)
                        }
                        deferred.reject(response.data);
                    }
                }, function(err) {
                    $ionicLoading.hide();
                    deferred.reject(err);
                })
            return deferred.promise;
        }

        function popupError(responseCode) {
            popup.alert(responseCode)
        }

        return {
            post: post,
            get: get
        };
    }
})();



(function() {
    'use strict';
    angular
        .module('ydApp')
        .factory('Cameranav', Cameranav);

    function Cameranav($cordovaCamera, $ionicPlatform, popup) {
        function getByPhoto(successCall, errorCall) {
            get(successCall, errorCall, {
                quality: 70,
                destinationType: 1,
                sourceType: 0,
                allowEdit: false,
                encodingType: 0,
                saveToPhotoAlbum: false,
                targetWidth: 1000,
                targetHeight: 1000,
                mediaType: 0
            });
        }

        function getByVideo(successCall, errorCall) {
            get(successCall, errorCall, {
                quality: 70,
                destinationType: 1,
                sourceType: 0,
                encodingType: 0,
                saveToPhotoAlbum: false,
                targetWidth: 1000,
                targetHeight: 1000,
                mediaType: 1
            });
        }

        function getByCamera(successCall, errorCall) {
            get(successCall, errorCall, {
                destinationType: 1,
                sourceType: 1,
                encodingType: 0,
                saveToPhotoAlbum: false
            });
        }

        function get(successCall, errorCall, options) {
            if (window.cordova) {
                $ionicPlatform.ready(function() {
                    $cordovaCamera.getPicture(options).then(function(imageUri) {
                        console.log(imageUri)
                        if (successCall) {
                            successCall(imageUri);
                        }
                    }, function(err) {
                        console.log("err:" + err)
                        if (errorCall) {
                            errorCall(err);
                        }
                    });
                });
            } else {
                if (successCall) {
                    successCall("uploadImg");
                }
            }
        }

        function getPicture(successCall, errorCall) {
            popup.sheet("选择图片", [
                { text: "相册" },
                { text: "相机" }
            ], function(index) {
                if (index == 0) {
                    getByPhoto(successCall, errorCall);
                } else {
                    getByCamera(successCall, errorCall);
                }
            })
        }

        function getSource(successCall, errorCall) {
            console.log("sss")
            popup.sheet("选择图片", [
                { text: "相册" },
                { text: "视频" },
                { text: "相机" }
            ], function(index) {
                if (index == 0) {
                    getByPhoto(successCall, errorCall);
                } else if (index == 1) {
                    getByVideo(function(uri) {
                        successCall(uri, true);
                    }, errorCall);
                } else {
                    getByCamera(successCall, errorCall);
                }
            })
        }
        return {
            getPicture: getPicture,
            getSource: getSource
        }
    }
})();


(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('fileTransfer', fileTransfer);

    function fileTransfer($ionicPlatform, $cordovaFileTransfer, xhr, localStore) {
        function upload(uri, id, successCall, errorCall, progressCall) {
            if (window.cordova) {
                $ionicPlatform.ready(function() {
                    var imageUpload = config.api + "HealthInquiry/com/uploadImage?id=" + id;
                    var params = new Object();

                    $cordovaFileTransfer.upload(imageUpload, uri, params)
                        .then(function(result) {
                            console.log(JSON.stringify(result))
                            successCall(eval("(" + result.response + ")"));
                        }, function(err) {
                            console.log(JSON.stringify(err))
                            if (errorCall) {
                                errorCall(err);
                            };
                        }, function(progress) {
                            if (progressCall) {
                                progressCall(progress);
                            };
                        });
                });
            } else {
                successCall({ fileName: uri });
            }
        }
        return {
            upload: upload
        };
    }
})();


(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('datePicker', datePicker);

    function datePicker($cordovaDatePicker, $ionicPlatform) {
        function show(callback, type) {
            if (window.cordova) {
                $ionicPlatform.ready(function() {
                    var options = {
                        date: new Date("1990-01-01"),
                        mode: type || 'date', // or 'time'
                        doneButtonLabel: '确认',
                        doneButtonColor: '#000000',
                        cancelButtonLabel: '取消',
                        cancelButtonColor: '#000000',
                        locale: "zh-cn"
                    };
                    $cordovaDatePicker.show(options).then(function(date) {
                        callback(getDateFormat(date, type || 'date'));
                    });
                });
            } else {
                callback(getDateFormat(new Date()));
            }
        }

        function getDateFormat(date, type) {
            if (type = "date") {
                return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            } else {
                return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
            }

        }
        return {
            show: show
        }
    }
})();


(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('geoService', geoService);

    function geoService($cordovaGeolocation, $ionicPlatform, Wgs2Mars, $q) {
        function get(callback) {
            var defer = $q.defer();
            if (window.cordova) {
                $ionicPlatform.ready(function() {
                    var posOptions = {
                        maximumAge: 3000,
                        timeout: 5000,
                        enableHighAccuracy: true
                    };
                    $cordovaGeolocation.getCurrentPosition(posOptions).then(function(position) {
                        var loc = Wgs2Mars.transform(
                            position.coords.longitude,
                            position.coords.latitude);
                        defer.resolve({
                            lng: loc.lng,
                            lat: loc.lat
                        })
                    }, function(err) {
                        console.error(JSON.stringify(err))
                        defer.reject(err);
                    });
                });
            } else {
                defer.resolve({
                    lng: "118.769417",
                    lat: "32.04737"
                })
            }
            return defer.promise;
        }
        return {
            get: get
        };
    }
})();



(function() {
    'use strict'
    angular
        .module('ydApp')
        .factory('Wgs2Mars', Wgs2Mars);

    function Wgs2Mars() {

        var PI = 3.14159265358979324;
        var a = 6378245.0;
        var ee = 0.00669342162296594323;

        function Rectangle(lng1, lat1, lng2, lat2) {
            this.west = Math.min(lng1, lng2);
            this.north = Math.max(lat1, lat2);
            this.east = Math.max(lng1, lng2);
            this.south = Math.min(lat1, lat2);
        }

        function isInRect(rect, lon, lat) {
            return rect.west <= lon && rect.east >= lon && rect.north >= lat && rect.south <= lat;
        }
        //China region - raw data
        var region = [
            new Rectangle(79.446200, 49.220400, 96.330000, 42.889900),
            new Rectangle(109.687200, 54.141500, 135.000200, 39.374200),
            new Rectangle(73.124600, 42.889900, 124.143255, 29.529700),
            new Rectangle(82.968400, 29.529700, 97.035200, 26.718600),
            new Rectangle(97.025300, 29.529700, 124.367395, 20.414096),
            new Rectangle(107.975793, 20.414096, 111.744104, 17.871542)
        ];
        //China excluded region - raw data
        var exclude = [
            new Rectangle(119.921265, 25.398623, 122.497559, 21.785006),
            new Rectangle(101.865200, 22.284000, 106.665000, 20.098800),
            new Rectangle(106.452500, 21.542200, 108.051000, 20.487800),
            new Rectangle(109.032300, 55.817500, 119.127000, 50.325700),
            new Rectangle(127.456800, 55.817500, 137.022700, 49.557400),
            new Rectangle(131.266200, 44.892200, 137.022700, 42.569200)
        ];

        function isInChina(lon, lat) {
            for (var i = 0; i < region.length; i++) {
                if (isInRect(region[i], lon, lat)) {
                    for (var j = 0; j < exclude.length; j++) {
                        if (isInRect(exclude[j], lon, lat)) {
                            return false;
                        }
                    }
                    return true;
                }
            }
            return false;
        }

        function transformLat(x, y) {
            var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
            ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
            ret += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
            return ret;
        }

        function transformLon(x, y) {
            var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
            ret += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
            ret += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
            ret += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
            return ret;
        }

        // World Geodetic System ==> Mars Geodetic System
        function transform(wgLon, wgLat) {
            var mgLoc = {};
            if (!isInChina(wgLon, wgLat)) {
                mgLoc = {
                    lat: wgLat,
                    lng: wgLon
                };
                return mgLoc;
            }
            var dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
            var dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
            var radLat = wgLat / 180.0 * PI;
            var magic = Math.sin(radLat);
            magic = 1 - ee * magic * magic;
            var sqrtMagic = Math.sqrt(magic);
            dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * PI);
            dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * PI);
            mgLoc = {
                lat: wgLat + dLat,
                lng: wgLon + dLon
            };
            return mgLoc;
        }
        return {
            transform: transform
        };
    };
})();



(function() {
    'use strict'
    angular
        .module('ydApp')
        .service('chatInterval', chatInterval);

    function chatInterval() {
        this.interval = {};
    }
})();

(function() {
    'use strict'
    angular.module('ydApp')
        .factory('pay', pay);

    function pay($cordovaToast) {

        function alipay(subject, body, price, tradeNo, successCall, errorCall) {
            var myDate = new Date();
            var alipay = navigator.alipay;
            console.log(subject);
            console.log(body);
            console.log(price);
            console.log(tradeNo);

            alipay.pay({
                "seller": "nanjingeasygoing@163.com",
                // "seller": "3023819262@qq.com",
                "subject": subject,
                "body": body,
                "price": price,
                "tradeNo": tradeNo,
                "timeout": '30m',
                "notifyUrl": config.api + "HealthInquiry/com/alipay/getAliPay"
            }, function(resultStatus) {
                if (successCall) {
                    successCall(resultStatus)
                }
                console.log(resultStatus);
            }, function(message) {
                if (errorCall) {
                    errorCall(message);
                }
                $cordovaToast.showShortCenter("支付失败，请稍后再试");
                console.log(message);
            });
        }
        return {
            alipay: alipay
        };
    }


})();
